package com.sun.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.reggie.common.R;
import com.sun.reggie.entity.Category;
import com.sun.reggie.entity.Dish;
import com.sun.reggie.entity.DishFlavor;
import com.sun.reggie.entity.dto.DishDto;
import com.sun.reggie.service.CategoryService;
import com.sun.reggie.service.DishFlavorService;
import com.sun.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author sun
 * @version 1.0
 */

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    DishService dishService;

    @Autowired
    DishFlavorService dishFlavorService;

    @Autowired
    CategoryService categoryService;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info("添加的菜品：",dishDto.toString());

        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");

    }

    @GetMapping("/page")
    public R<Page<DishDto>> page2(@RequestParam("page") int page, int pageSize,String name) {
//        page = 1,pageSize = 10,name=长沙
        log.info("page = {},pageSize = {},name={}", page, pageSize,name);
        //构造分页构造器
        Page<DishDto> dishDtoPage = new Page<DishDto>(page, pageSize);
        dishDtoPage = dishService.pageDishDto(dishDtoPage,name);
        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品停售在售状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status, @RequestParam("ids") List<Long> ids){
        log.info("设置状态：",status);
        log.info("修改字段id",ids);
        List<Dish> dishes = dishService.listByIds(ids);

        List<Dish> collect = dishes.stream().map(s -> {
            s.setStatus(status);
            return s;
        }).collect(Collectors.toList());

        boolean b = dishService.updateBatchById(collect);
        return b?R.success("操作成功"):R.error("操作失败");
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info("dishDto = {}",dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }

    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam("ids") List<Long> ids){
        log.info("ids = {}",ids);
        boolean b = dishService.removeByIdsWithFlavor(ids);
        return b?R.success("删除成功"):R.error("删除失败");
    }

    /**
     * 回收删除菜品分页显示
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/recyclePage")
    public R<Page<DishDto>> page3(@RequestParam("page") int page, int pageSize,String name) {
//        page = 1,pageSize = 10,name=长沙
        log.info("page = {},pageSize = {},name={}", page, pageSize,name);
        //构造分页构造器
        Page<DishDto> dishDtoPage = new Page<DishDto>(page, pageSize);
        dishDtoPage = dishService.pageRecycleDishDto(dishDtoPage,name);
        return R.success(dishDtoPage);
    }

    /**
     * 恢复对应菜品数据
     * @param ids
     * @return
     */
    @DeleteMapping("/recycle")
    public R<String> recycle(@RequestParam("ids") List<Long> ids){
        log.info("ids = {}",ids);
        boolean b = dishService.recycleByIdsWithFlavor(ids);
        return b?R.success("恢复成功"):R.error("恢复失败");
    }

    /**
     * 根据条件查询对应的菜品数据
     * @param dish
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "dishCache",key = "#dish.categoryId + '_' + #dish.status")
    public R<List<DishDto>> list(Dish dish){
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }

}